package cn.com.franke.concurrency;

import com.google.common.base.Throwables;
import com.google.common.util.concurrent.*;
import org.junit.Test;

import java.util.concurrent.Callable;
import java.util.concurrent.Executors;

/**
 * Created by liuzh on 2017/5/1.
 */
public class ListenableFutureTest {
    // 强烈地建议你在代码中多使用ListenableFuture来代替JDK的 Future, 因为：
//    大多数Futures 方法中需要它。
//    转到ListenableFuture 编程比较容易。
//    Guava提供的通用公共类封装了公共的操作方方法，不需要提供Future和ListenableFuture的扩展方法。
//    ListenableFuture的创建
//    对应JDK中的 ExecutorService.submit(Callable) 提交多线程异步运算的方式，Guava 提供了ListeningExecutorService 接口,
//    该接口返回 ListenableFuture 而相应的 ExecutorService 返回普通的 Future。将 ExecutorService 转为 ListeningExecutorService，
//    可以使用MoreExecutors.listeningDecorator(ExecutorService)进行装饰。
    @Test
    public void test1() {
        ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));
        ListenableFuture<ResultInfo> explosion = service.submit(new Callable() {
            public ResultInfo call() {
                if(1/0==1){
                    System.out.println();
                }
                ResultInfo res = new ResultInfo();
                res.setResCode("0000");
                res.setResDesc("成功");
                return res;
            }
        });
//        explosion.addListener();
        Futures.addCallback(explosion, new FutureCallback<ResultInfo>() {
            // we want this handler to run immediately after we push the big red button!
            public void onSuccess(ResultInfo explosion) {
                System.out.println("onSuccess......"+explosion.toString());
            }

            public void onFailure(Throwable thrown) {
                System.out.println("onFailure......"+ Throwables.getStackTraceAsString(thrown)); // escaped the explosion!
            }
        });
    }
    class ResultInfo{
        private String resCode;
        private  String resDesc;

        public String getResDesc() {
            return resDesc;
        }

        public void setResDesc(String resDesc) {
            this.resDesc = resDesc;
        }

        @Override
        public String toString() {
            return "ResultInfo{" +
                    "resCode='" + resCode + '\'' +
                    ", resDesc='" + resDesc + '\'' +
                    '}';
        }

        public String getResCode() {

            return resCode;
        }

        public void setResCode(String resCode) {
            this.resCode = resCode;
        }
    }
}
